﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraPlay : MonoBehaviour {

    public int CameraWidth = 3840;
    public int CameraHeight = 2160;
    public int fps = 15;
    string deviceName;
    WebCamTexture tex;
    Texture2D newTexture;

	// Use this for initialization
	void Start () {
        StartCoroutine(PlayCamera());
	}
	
	// Update is called once per frame
	void Update () {
        UpdateCameraTexture();
	}

    IEnumerator PlayCamera()
    {
        yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
        if (Application.HasUserAuthorization(UserAuthorization.WebCam))
        {
            WebCamDevice[] devices = WebCamTexture.devices;

            if (devices.Length != 0)
            {
                foreach (WebCamDevice cam in devices)
                {
                    Debug.Log(cam.name);
                    if(cam.name == "Logitech BRIO")
                        deviceName = cam.name;
                }
                tex = new WebCamTexture(deviceName, CameraWidth, CameraHeight, fps);
                newTexture = new Texture2D(CameraWidth, CameraHeight, TextureFormat.RGBA32, false);
                tex.Play();
            }
            else
            {
                Debug.Log("No Camera Loading!!!");
            }
             
        }
    }

    void UpdateCameraTexture()
    {
        gameObject.GetComponent<Renderer>().material.mainTexture = tex;

    }
}
